import xmlrpclib
import sys
import cgi
import logging
from google.appengine.ext import db
from datetime import datetime
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from com.jumang.model.note import note
from com.jumang.model.NoteCategory import NoteCategory
from config import realConfig

def check_api_user_pass(username,password):
##	logging.warning(username+':'+password)
	if username == realConfig.getUserName() and password == realConfig.getPostPassword():
		return True
	else :
		return False

def blogger_getUsersBlogs(discard, username, password):
	if not check_api_user_pass(username, password):
		raise Exception, 'access denied'
	
	myConfig=realConfig
	return [{'url' : myConfig.siteHome, 'blogid' : 'JumangLog', 'blogName' : myConfig.siteTitle}]

def metaWeblog_newPost(blogid, username, password, content, publish):
	user = check_api_user_pass(username, password)
	if not user:
		raise Exception, 'access denied'
	postTag=''
	if publish:
		if content.has_key('categories'):
			tags = content['categories']
			if tags:
				postTag=tags[0]
		else:
			pass
		post = note(title = content['title'],
			content = db.Text(content['description']),isPublic=True)
		categories=NoteCategory.all().filter('name =',postTag).fetch(1)
		if categories:
			post.jumCategory=categories[0]
		post.put()
		return str(post.key().id())
	else:
		return 'notpublished'

def metaWeblog_editPost(postid, username, password, content, publish):
	user = check_api_user_pass(username, password)
	if not user:
		raise Exception, 'access denied'

	postTag=''
	if publish:
		if content.has_key('categories'):
			tags = content['categories']
			if tags:
				postTag=tags[0]
		else:
			pass
		post=note.get_by_id(int(postid))
		if post:
			post.title = content['title']
			post.content = db.Text(content['description'])
			categories=NoteCategory.all().filter('name =',postTag).fetch(1)
			if categories:
				post.jumCategory=categories[0]
			post.isPublic=True
			post.put()
			return True
		else:
			return False
	else:
		return False

def metaWeblog_getCategories(blogid, username, password):
	user = check_api_user_pass(username, password)
	if not user:
		raise Exception, 'access denied'

	categories = []
	all_tags = NoteCategory.all()
	for tag in all_tags:
		categories.append({'description' : unicode(tag.describe), 'title' : tag.name})

	return categories

def metaWeblog_getPost(postid, username, password):
	user = check_api_user_pass(username, password)
	if not user:
		raise Exception, 'access denied'

	post = note.get_by_id(int(postid))

	return {
			'postid' : postid,
			'dateCreated' : post.createTime,
			'title' : post.title,
			'description' : unicode(post.content),
			'categories' : post.jumCategory.name,
			'publish' : True,
			}

def metaWeblog_getRecentPosts(blogid, username, password, numberOfPosts):
	notes = note.all().order('-createTime').fetch(20)
	result = []
	for post in notes:
##		logging.warning(post.content)
		result.append({
			'postid' : str(post.key().id()),
			'dateCreated' : post.createTime,
			'title' : post.title,
			'description' : unicode(post.content),
			'categories' : post.jumCategory.name,
			'publish' : True,
			})

	return result


def blogger_deletePost(appkey, postid, username, password, publish):
	user = check_api_user_pass(username, password)
	if not user:
		raise Exception, 'access denied'
	if publish:
		post=note.get_by_id(int(postid))
		if post:
			post.isPublic=False
			post.put()
			return True
		else:
			return False
	else:
		return False

class PLOGXMLRPCDispatcher(SimpleXMLRPCDispatcher):
	def __init__(self, funcs):
		SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
		self.funcs = funcs
##		logging.warning(funcs)

dispatcher = PLOGXMLRPCDispatcher({
	'blogger.getUsersBlogs':blogger_getUsersBlogs,
	'blogger.deletePost':blogger_deletePost,
	'metaWeblog.newPost':metaWeblog_newPost,
	'metaWeblog.editPost':metaWeblog_editPost,
	'metaWeblog.getCategories': metaWeblog_getCategories,
	'metaWeblog.getCategoryList': metaWeblog_getCategories,
	'metaWeblog.getPost':metaWeblog_getPost,
	'metaWeblog.getRecentPosts':metaWeblog_getRecentPosts,
	})

